﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;




//仅当角色移动时，才启用该脚本
public class WalkRange : MonoBehaviour
{
    //角色能跨越的斜坡高度(以Unity 单位为标准)
    public float slopeHigh = 0.2f;

    private BoxCollider2D boxCollider2D;
    private SpriteRenderer spriteRenderer;

    //默认Unity 单位与图片像素比为 1 : 100 
    private float pixelsPerUnit = 100.0f;
    private Rect spriteRect;


    private void Start()
    {
        boxCollider2D = GetComponent<BoxCollider2D>();
        spriteRenderer = transform.parent.GetComponent<SpriteRenderer>();
    }


    private void Update()
    {
        Rect texRect = spriteRenderer.sprite.textureRect;

        //角色SpriteRenderer 组件的Sprite 被切换，重新计算boxCollider2D 位置以及boxCollider2D 大小
        if (!spriteRect.Equals(texRect))
        {
            //角色宽高
            float roleWidth = (texRect.width - texRect.x) / pixelsPerUnit;
            float roleHeight = (texRect.height - texRect.y) / pixelsPerUnit;

            //默认锚点(原坐标)处于图片中心
            //所以偏移(roleHeight/2)个单位到图片最底部,再算上boxCollider2D (size)高度一半的量，得出脚部y轴位置
            transform.position = Vector3.down * ((roleHeight - slopeHigh) / 2);
            boxCollider2D.size = new Vector2(roleWidth, slopeHigh);

            spriteRect = texRect;
        }
    }
}
 
